package cn.zf233.jwtshiro.config.shiro;

import cn.zf233.jwtshiro.service.UserService;
import cn.zf233.jwtshiro.util.JwtUtil;
import cn.zf233.jwtshiro.util.RedisUtil;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Set;

/**
 * Created by zf233 on 2021/7/12
 */
@Slf4j
public class JwtRealm extends AuthorizingRealm {

    private static final String jwt_black_list_redis_set_key = "jwtRedisSetKey";

    private final UserService userService;

    private final RedisUtil redisUtil;

    public JwtRealm(UserService userService, RedisUtil redisUtil) {
        this.userService = userService;
        this.redisUtil = redisUtil;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getPrincipal();
        log.info("准备验证用户凭证:'{}'", token);
        String msg;
        if (StringUtils.isBlank(token)) {
            msg = "未携带用户凭证";
        } else {
            try {
                JwtUtil.verify(token);
                log.info("用户凭证验证成功，ID:{}", JwtUtil.getUserIdByToken(token));
                return new SimpleAuthenticationInfo(token, token, getName());
            } catch (TokenExpiredException e) {
                log.info("凭证已经过期");
                msg = "凭证已经过期";
            } catch (SignatureVerificationException e) {
                log.info("凭证签名错误");
                msg = "凭证签名错误";
            } catch (AlgorithmMismatchException e) {
                log.info("凭证加密算法不匹配");
                msg = "凭证加密算法不匹配";
            } catch (Exception e) {
                log.info("无效的凭证");
                msg = "无效的凭证";
            }
        }
        log.info("抛出异常并填充错误信息");
        throw new AuthenticationException(msg);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
        String token = (String) collection.getPrimaryPrincipal();
        Long userId = JwtUtil.getUserIdByToken(token);
        log.info("用户:'{}'授权", userId);
        Set<String> roleSet = userService.getRoleByUserId(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // TODO 查询数据库中用户角色和权限列表, 放入SimpleAuthorizationInfo中(自己实现)
        Set<String> permissionSet = userService.getPermissionByUserId(userId);
        info.setRoles(roleSet);
        info.setStringPermissions(permissionSet);
        return info;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
}